package com.wodan.zhongjinjicang.common.utils;

import com.sun.org.apache.xml.internal.security.utils.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.util.Random;

/**
 * 主要提供DES加密和解密方法。
 * 
 * @author suchangjun
 * 
 */
public class MyDes {

    public static void main(String[] args) {
        for (int i = 1; i < 10; i++) {
            String key = getRandomStr(8);
            String wantEncrypeStr = getRandomStr(100 * i);

            String afterEnStr = encryptDES(wantEncrypeStr, key);

            String afterDeStr = decryptDES(afterEnStr, key);

            // System.out.println("要加密的明文是：  "+wantEncrypeStr);
            // System.out.println("密文是：     "+afterEnStr);
            System.out.println("加密的密钥是：     " + key);
            System.out.println("明文长度：  " + wantEncrypeStr.length());
            System.out.println("密文长度：     " + afterEnStr.length());
            System.out.println("密文长度相对明文增加：     "
                    + ((afterEnStr.length() - wantEncrypeStr.length()) *100/ wantEncrypeStr.length())+"%");

            System.out.println("解密结果是否正确：     " + afterDeStr.equals(wantEncrypeStr));
        }

    }

    /**
     * 解密，注意密码只能是8字节，是64位。
     * 
     * @param decrypeString
     *            要解密的密文,不能是空。
     * @param decrypetKey
     *            密钥8个字节，是64位。
     * @return
     * @throws Exception
     */
    public static String decryptDES(String decrypeString, String decrypetKey) {
        byte[] decryptedData = null;
        try {
            byte[] byteMi = Base64.decode(decrypeString);
            SecretKeySpec key = new SecretKeySpec(decrypetKey.getBytes(), DES);
            Cipher cipher = Cipher.getInstance(MODEL);
            cipher.init(Cipher.DECRYPT_MODE, key, IV_PARAM);
            decryptedData = cipher.doFinal(byteMi);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new String(decryptedData);
    }

    /**
     * 加密，注意密码只能是8字节，是64位,算法是DES,模式是CBC,填充是PKCS5Padding。
     * 
     * @param encrypeString
     *            要加密的明文，不能是空。
     * @param encrypetKey
     *            密钥8个字节，是64位。
     * @return
     * @throws Exception
     */
    public static String encryptDES(String encrypeString, String encrypetKey) {
        byte[] encryptedData = null;
        try {
            IvParameterSpec zeroIv = new IvParameterSpec(IV);
            SecretKeySpec key = new SecretKeySpec(encrypetKey.getBytes(), DES);
            Cipher cipher = Cipher.getInstance(MODEL);
            cipher.init(Cipher.ENCRYPT_MODE, key, zeroIv);
            encryptedData = cipher.doFinal(encrypeString.getBytes());

        } catch (Exception e) {
            e.printStackTrace();
        }
        return Base64.encode(encryptedData);
    }

    /**
     * 获取随机字符串。
     * 
     * @param length
     * @return
     */
    public static String getRandomStr(int length) {
        if (length < 1) {
            return null;
        }
        Random random = new Random();
        char[] buf = new char[length];
        int index = 0;
        for (int i = 0; i < length; i++) {
            index = random.nextInt(SOURCE.length);
            buf[i] = SOURCE[index];
        }
        return new String(buf);
    }

    private static final String DES = "DES";

    private static final String MODEL = "DES/CBC/PKCS5Padding";

    private static final byte[] IV = { 1, 2, 3, 4, 5, 9, 7, 8 };// 加密的初始向量。

    private static final IvParameterSpec IV_PARAM = new IvParameterSpec(IV);

    private static final char[] SOURCE = "123456789abcdefghijklmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ"
            .toCharArray();

}
